package com.tianzeculture.stagebao.activity.home;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.renderscript.RenderScript;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.accessibility.AccessibilityManagerCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.tianzeculture.stagebao.R;
import com.tianzeculture.stagebao.activity.artist.AddTalentActivity;
import com.tianzeculture.stagebao.activity.artist.ArtistActivity;
import com.tianzeculture.stagebao.activity.artist.MyArtistActivity;
import com.tianzeculture.stagebao.activity.artist.PublishWorksActivity;
import com.tianzeculture.stagebao.activity.business.PublishNoticeActivity;
import com.tianzeculture.stagebao.activity.business.PublishNoticeTwoActivity;
import com.tianzeculture.stagebao.activity.home.adapter.ConversationListAdapterEx;
import com.tianzeculture.stagebao.activity.home.fragment.HomeFragment;
import com.tianzeculture.stagebao.activity.home.fragment.MessageFragment;
import com.tianzeculture.stagebao.activity.home.fragment.MyFragment;
import com.tianzeculture.stagebao.activity.home.fragment.NoticeFragment;
import com.tianzeculture.stagebao.activity.home.fragment.OrderFragment;
import com.tianzeculture.stagebao.activity.home.fragment.TalentFragment;
import com.tianzeculture.stagebao.activity.login.LoginActivity;
import com.tianzeculture.stagebao.application.StageBaoApplication;
import com.tianzeculture.stagebao.base.BaseActivity;
import com.tianzeculture.stagebao.bean.ArtistsDetailedBean;
import com.tianzeculture.stagebao.bean.ReplyBean;
import com.tianzeculture.stagebao.bean.RongBean;
import com.tianzeculture.stagebao.bean.RongIdBean;
import com.tianzeculture.stagebao.bean.User;
import com.tianzeculture.stagebao.net.OtherRestUsage;
import com.tianzeculture.stagebao.net.UserRestUsage;
import com.tianzeculture.stagebao.network.Request;
import com.tianzeculture.stagebao.network.enity.MSG;
import com.tianzeculture.stagebao.network.util.ToastUtil;
import com.tianzeculture.stagebao.util.SpUtils;
import com.tianzeculture.stagebao.util.Util;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationListFragment;
import io.rong.imkit.model.UIConversation;
import io.rong.imlib.IFwLogCallback;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.UserInfo;
import io.rong.message.TextMessage;
import io.rong.photoview.log.LoggerDefault;

import static com.tianzeculture.stagebao.net.base.AppBaseRestUsageV2.PICTURE_URL;

public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    private List<Fragment> fragments;
    @BindView(R.id.rgMain)
    RadioGroup rgMain;
    @BindView(R.id.rbtnHome)
    RadioButton rbtnHome;
    @BindView(R.id.rbtnNotice)
    RadioButton rbtnNotice;
    @BindView(R.id.rbtnTalent)
    RadioButton rbtnTalent;
    @BindView(R.id.rbtnOrder)
    RadioButton rbtnOrder;
    @BindView(R.id.rbtnMy)
    RadioButton rbtnMy;

    @BindView(R.id.ibtnPublish)
    ImageButton ibtnPublish;

    public static Activity instance;
//    @BindView(R.id.statusView)
//    View statusView;

    private ConversationListFragment mConversationListFragment = null;
    private Conversation.ConversationType[] mConversationsTypes = null;
    @Request
    UserRestUsage userRestUsage = null;
    @Request
    OtherRestUsage otherRestUsage = null;
    private int getUserInfoId = 0;
    private int myInfoId = 1;
    private int getRongUserId = 9;
    private int getReplyId = 12;
    private int iconClickId = 15;
    private String userId;
    private String replyRid;
    private int tokenId = 8;

    @Override
    public void initUI() {
        super.initUI();
//        ViewGroup.LayoutParams layoutParams = statusView.getLayoutParams();
//        layoutParams.height = getStatusHeight(this);
//        statusView.setLayoutParams(layoutParams);
        instance = this;
        getRongFragment();
        addFragment();
        userRestUsage.getToken(tokenId, Util.UserId);

////        自动回复
//        RongIM.setOnReceiveMessageListener(new RongIMClient.OnReceiveMessageListener() {
//            /**
//             * 收到消息的处理。
//             * @param message 收到的消息实体。
//             * @param left 剩余未拉取消息数目。
//             * @return
//             */
//            @Override
//            public boolean onReceived(Message message, int left) {
//                if ((boolean) (SpUtils.get(MainActivity.this, "isReply", false))) {
//                    TextMessage textMessage = new TextMessage((String) (SpUtils.get(MainActivity.this, "replyContent", "")));
//
//                    RongIMClient.getInstance().sendMessage(Conversation.ConversationType.PRIVATE, message.getTargetId(), textMessage, null, null, new IRongCallback.ISendMessageCallback() {
//                        @Override
//                        public void onAttached(Message message) {
//                            // 消息成功存到本地数据库的回调
//                        }
//
//                        @Override
//                        public void onSuccess(Message message) {
//                            // 消息发送成功的回调
//                        }
//
//                        @Override
//                        public void onError(Message message, RongIMClient.ErrorCode errorCode) {
//                            // 消息发送失败的回调
//                        }
//                    });
//                }
////        开发者根据自己需求自行处理
//                return false;
//            }
//        });

        //融云会话列表监听
        RongIM.getInstance().setConversationListBehaviorListener(new RongIM.ConversationListBehaviorListener() {
            @Override
            public boolean onConversationPortraitClick(Context context, Conversation.ConversationType conversationType, String s) {
                return false;
            }

            @Override
            public boolean onConversationPortraitLongClick(Context context, Conversation.ConversationType conversationType, String s) {
                return false;
            }

            @Override
            public boolean onConversationLongClick(Context context, View view, UIConversation uiConversation) {
                return false;
            }

            @Override
            public boolean onConversationClick(Context context, View view, UIConversation uiConversation) {
                replyRid = uiConversation.getConversationTargetId();
                otherRestUsage.getReply(getReplyId, uiConversation.getConversationTargetId());
                return false;
            }
        });

        //融云会话界面监听
        RongIM.getInstance().setConversationClickListener(new RongIM.ConversationClickListener() {
            @Override
            public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo, String s) {
                userRestUsage.getUserInfo(iconClickId, userInfo.getUserId());
                return false;
            }

            @Override
            public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo, String s) {
                return false;
            }

            @Override
            public boolean onMessageClick(Context context, View view, Message message) {
                return false;
            }

            @Override
            public boolean onMessageLinkClick(Context context, String s, Message message) {
                return false;
            }

            @Override
            public boolean onMessageLongClick(Context context, View view, Message message) {
                return false;
            }
        });


        RongIM.getInstance().enableUnreadMessageIcon(true);//显示未读消息数目
        RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {
            @Override
            public io.rong.imlib.model.UserInfo getUserInfo(String s) {
                userId = s;
                userRestUsage.getUserInfo(getUserInfoId, s);
                return null;
            }
        }, true);
        if (Util.JOB == 0) {
            rbtnNotice.setVisibility(View.VISIBLE);
            rbtnTalent.setVisibility(View.GONE);
        } else {
            rbtnNotice.setVisibility(View.GONE);
            rbtnTalent.setVisibility(View.VISIBLE);
        }
        //设置默认被选中的RadioButton
        rgMain.check(R.id.rbtnHome);
        switchFragment(0);
//        statusView.setBackgroundResource(R.color.colorGray_F8);
        rgMain.setOnCheckedChangeListener(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        userRestUsage.myInfo(myInfoId, Util.UserId);
    }

    private Fragment getRongFragment() {
        if (mConversationListFragment == null) {
            ConversationListFragment listFragment = new ConversationListFragment();
            listFragment.setAdapter(new ConversationListAdapterEx(RongContext.getInstance()));
            Uri uri;

            uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
                    .appendPath("conversationlist")
                    .appendQueryParameter(Conversation.ConversationType.PRIVATE.getName(), "false") //设置私聊会话是否聚合显示
                    .appendQueryParameter(Conversation.ConversationType.GROUP.getName(), "false")//群组
                    .appendQueryParameter(Conversation.ConversationType.PUBLIC_SERVICE.getName(), "false")//公共服务号
                    .appendQueryParameter(Conversation.ConversationType.APP_PUBLIC_SERVICE.getName(), "false")//订阅号
                    .appendQueryParameter(Conversation.ConversationType.SYSTEM.getName(), "true")//系统
                    .build();
            mConversationsTypes = new Conversation.ConversationType[]{Conversation.ConversationType.PRIVATE,
                    Conversation.ConversationType.GROUP,
                    Conversation.ConversationType.PUBLIC_SERVICE,
                    Conversation.ConversationType.APP_PUBLIC_SERVICE,
                    Conversation.ConversationType.SYSTEM
            };

            listFragment.setUri(uri);
            mConversationListFragment = listFragment;
            return listFragment;
        } else {
            return mConversationListFragment;
        }
    }


    @OnClick(R.id.ibtnPublish)
    public void publish(View view) {
//        Intent intent = new Intent(MainActivity.this, AddTalentActivity.class);
//        startActivity(intent);

        if (Util.JOB == 1) {
            Intent intent = new Intent(MainActivity.this, PublishNoticeActivity.class);
            startActivity(intent);
        } else {
            if (Util.user == null)
                Util.user = new User();
            if ("1".equals(Util.ALENT)) {//已加入人才库
//            if (true) {//已加入人才库
                Intent intent = new Intent(MainActivity.this, PublishWorksActivity.class);
                startActivity(intent);
            } else {
                Intent intent = new Intent(MainActivity.this, AddTalentActivity.class);
                startActivity(intent);
            }
        }
    }


    //    private class MyReceiveMessageListener implements RongIMClient.OnReceiveMessageListener {
//
//
//    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent i = new Intent(Intent.ACTION_MAIN);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.addCategory(Intent.CATEGORY_HOME);
            startActivity(i);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    /**
     * 获得状态栏的高度
     *
     * @param context
     * @return
     */
    public int getStatusHeight(Context context) {

        int statusHeight = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height")
                    .get(object).toString());
            statusHeight = context.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusHeight;
    }


    @Override
    public void refreshUI(int taskId, MSG msg) {
        super.refreshUI(taskId, msg);
        if (taskId == iconClickId) {
            if (msg.getData()) {
                if (msg.getObj() == null)
                    return;
                RongBean bean = (RongBean) msg.getObj();
                if (!Util.UserId.equals(bean.getId()))
                    startActivity(new Intent(this, ArtistActivity.class).putExtra("otherId", bean.getId()).putExtra("isRM", true));
            }
        }
        if (taskId == getUserInfoId) {
            if (msg.getData()) {
                if (msg.getObj() == null)
                    return;
                RongBean bean = (RongBean) msg.getObj();
                RongIM.getInstance().refreshUserInfoCache(new UserInfo(userId, bean.getNickname(), Uri.parse(PICTURE_URL + bean.getImgurl())));
            }
        }
        if (taskId == myInfoId) {
            if (msg.getData()) {
                ArtistsDetailedBean bean = (ArtistsDetailedBean) msg.getObj();
                Util.ALENT = bean.getUser().getAlent();
                Util.user.setAlent(bean.getUser().getAlent());
            }
        }
        if (taskId == tokenId) {
            if (msg.getData()) {
                if (msg.getObj() != null) {
                    RongIdBean resultBean = (RongIdBean) msg.getObj();
                    connect(resultBean.getToken());
                }
            }
        }
        if (taskId == getRongUserId) {
            if (msg.getData()) {
                if (msg.getObj() != null) {
                    RongBean bean = (RongBean) msg.getObj();
                }
            }
        }
        if (taskId == getReplyId) {
            if (msg.getData()) {
                ReplyBean bean = (ReplyBean) msg.getObj();
                if (null == bean || 0 == bean.getAutoResponse())
                    return;
                TextMessage textMessage = new TextMessage(bean.getResponseMsg());
                io.rong.imlib.model.Message.ReceivedStatus receivedStatus = new io.rong.imlib.model.Message.ReceivedStatus(0);
                receivedStatus.setRead();
                RongIM.getInstance().insertIncomingMessage(Conversation.ConversationType.PRIVATE, replyRid, replyRid, receivedStatus, textMessage, null);
            }
        }
    }


    @Override
    protected int getLayoutResID() {
        return R.layout.activity_main;
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
        switch (checkedId) {
            case R.id.rbtnHome:
//                statusView.setVisibility(View.VISIBLE);
//                statusView.setBackgroundResource(R.color.colorGray_F8);
                switchFragment(0);
                break;
            case R.id.rbtnNotice:
//                statusView.setVisibility(View.VISIBLE);
//                statusView.setBackgroundResource(R.color.colorGray_F0);
                switchFragment(1);
                break;
            case R.id.rbtnTalent:
//                statusView.setVisibility(View.VISIBLE);
//                statusView.setBackgroundResource(R.color.colorGray_F0);
                switchFragment(1);
                break;
            case R.id.rbtnOrder:
//                statusView.setVisibility(View.VISIBLE);
//                statusView.setBackgroundResource(R.color.colorGray_F0);
                switchFragment(2);
                break;
            case R.id.rbtnMy:
//                statusView.setVisibility(View.GONE);
                switchFragment(3);
                break;
        }
    }

    /**
     * 创建fragment实例并把他们加入集合
     */
    public void addFragment() {
        fragments = new ArrayList<>();
        fragments.add(new HomeFragment());
        if (Util.JOB == 0) {//艺人
            fragments.add(new NoticeFragment());//招募
        } else {//商家
            fragments.add(new TalentFragment());//人才库
        }
//        fragments.add(new OrderFragment());
        fragments.add(mConversationListFragment);
//        fragments.add(new MessageFragment());
        fragments.add(new MyFragment());
    }

    /**
     * 点击切换fragment
     *
     * @param position
     */
    public void switchFragment(int position) {
        //开启事务
        FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        //遍历集合
        for (int i = 0; i < fragments.size(); i++) {
            Fragment fragment = fragments.get(i);
            if (i == position) {
                //显示fragment
                if (fragment.isAdded()) {
                    //如果这个fragment已经被事务添加,显示
                    fragmentTransaction.show(fragment);
                } else {
                    //如果这个fragment没有被事务添加过,添加
                    fragmentTransaction.add(R.id.fl_container, fragment);
                }
            } else {
                //隐藏fragment
                if (fragment.isAdded()) {
                    //如果这个fragment已经被事务添加,隐藏
                    fragmentTransaction.hide(fragment);
                }
            }
        }
        //提交事务
        fragmentTransaction.commit();
    }

    private void connect(String token) {

        if (getApplicationInfo().packageName.equals(StageBaoApplication.getCurProcessName(getApplicationContext()))) {

            RongIM.connect(token, new RongIMClient.ConnectCallback() {

                /**
                 * Token 错误。可以从下面两点检查 1.  Token 是否过期，如果过期您需要向 App Server 重新请求一个新的 Token
                 *                  2.  token 对应的 appKey 和工程里设置的 appKey 是否一致
                 */
                @Override
                public void onTokenIncorrect() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showShort(MainActivity.this, "token错误");
                        }
                    });
                }

                /**
                 * 连接融云成功
                 * @param userid 当前 token 对应的用户 id
                 */
                @Override
                public void onSuccess(String userid) {
                    Util.Rid = userid;
                    userRestUsage.getUserInfo(getRongUserId, userid);
//                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
//                    finish();
                }

                /**
                 * 连接融云失败
                 * @param errorCode 错误码，可到官网 查看错误码对应的注释
                 */
                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {
                    ToastUtil.showShort(MainActivity.this, "连接融云失败" + errorCode);
                }
            });
        }
    }
}